/*
 * @author zzr
 * @date: 2025/10/12  14:35
 * @description:
 */

/**
 * 给一个链表的头节点 head 和整数 val，删除链表中所有满足 node.val == val 的节点
 * 并返回新的头结点 head
 */
public class Demo3 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeElements(ListNode head, int val) {
         if (head == null) {
             return null;
         }
         ListNode prev = head;
         ListNode cur = head.next;

         while (cur != null) {
             if (cur.val == val) {
                 // 如果 cur 的值等于 val
                 // 删除 cur 节点
                 prev.next = cur.next;
             } else {
                 prev = cur;
             }
             cur = cur.next;
         }
         if (head.val == val) {
             head = head.next;
         }
         return head;
    }
}
